const { literal, Op, Sequelize } = require("sequelize");
const { User } = require('../models/index')

users =function(){}

users.regist = async (req, res, next) => {
	const { username, password } = req.body
	User.create({ username, password }).then((result)=>{
    	console.log('注册成功')
		  res.redirect('/login')
	}).catch((error)=>{
      console.log('注册失败')
		  res.redirect('/regist') 
    })  
};

users.login=function(ws,req){
  console.log('连接成功')
  ws.on('message', function (msg) {
    data = JSON.parse(msg)
    //console.log(msg)
    User.findOne({where:data,raw:true}).then((result)=>{
      if(result){
        console.log(result)
        ws.send('登录成功')
      }
      else ws.send('登录失败')
    }).catch((error)=>{
      console.log(error)
    })    
  })
  ws.send('连接成功')
  //console.log(req)
  //req.body为{}
}

/* 删除 */
users.delete = async (req, response, next) => {
	const { id } = req.body
	try {
		const data = await User.destroy({ where: { id } }); //直接删除
		response.send(success(data))
	} catch (error) {
		response.send(fail(error))
	}
};
users.update=async (req, response, next) => {
	const { id, title, content, inputValue } = req.body
	try {
		const data = await User.update({ title, content, inputValue }, { where: { id } });
		response.send(success(data))
	} catch (error) {
		response.send(fail(error))
	}
};
/* 获取所有 */
users.getall=async (req, response, next) => {
	try {
		const data = await User.findAll(); //获取所有
		response.send(success(data))
	} catch (error) {
		response.send(fail(error))
	}
};


/* 分页查询 */
users.list= async (req, response, next) => {
	const { title, pageSize, pageNum } = req.body
	try {
		let data = await User.findAndCountAll({
			where: {
				title: {
					[Op.like]: `%${title || ''}%`
				},
			},
			order: [['createTime', 'desc']],
			limit: pageSize || 10,
			offset: ((pageNum || 1) - 1) * (pageSize || 10),
		});
		response.send(success(data))
	} catch (error) {
		response.send(fail(error))
	}
};



module.exports = users;
